package com.study.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

public class MyConvert {
    /**
     * java对象转换为xml文件
     *
     * @param load    java对象.Class
     * @return xml文件的String
     */
    public static String beanToXml(Object obj, Class<?> load) {
        try {
            JAXBContext context = JAXBContext.newInstance(load);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            return writer.toString();
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }
        return "";
    }
}
